﻿using AutoControlSpectrum.Device;
using AutoControlSpectrum.EnumHelp;
using AutoControlSpectrum.Extensions;
using AutoControlSpectrum.Manufacturer;
using AutoControlSpectrum.Model;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tools.Enum;

namespace AutoControlSpectrum
{
    public partial class Index : Form
    {
        public Index()
        {
            InitializeComponent();

            nud_bjsmddsc.Value = AppSettings.Instance.Bjsmddsc;
            nud_szypddsc.Value = AppSettings.Instance.Szypddsc;
            nud_jsddsc.Value = AppSettings.Instance.Jsddsc;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 启动Socket服务
            SocketServer.Instance.MsgCallback = (msg) =>
            {
                // 客户端发送给服务的消息
                Invoke(new Action(() =>
                {
                    tbx_deviceMessages.AppendText(msg + Environment.NewLine);

                    //样品名称 = Administrator 96; 说明 = 样品 096 用户 Administrator 日期 星期五, 十一月 08 2024; Oppma = -3.98461E+17; Cppma = -32.3951; Oppma_2 = -8.3202E+16; Cppma_2 = -27.1882
                    var cells = msg.Split(new string[] { "(:)" }, StringSplitOptions.RemoveEmptyEntries).ToList();
                    var type = cells.First();

                    switch (type)
                    {
                        // 发送过来结果
                        case "SampleCalculateResult":

                            try
                            {
                                var sampleNo = DeviceControl.Instance.SampleNo;
                                var dic = cells.Last().Split(';').ToList().Select(p =>
                                {
                                    var temp = p.Split('=').ToList();
                                    return new KeyValuePair<string, string>(temp.First(), temp.Last());
                                });
                                var cppma = dic.ToList().FindLast(p => p.Key.Contains("Cppma")).Value;
                                var oppma = dic.ToList().FindLast(p => p.Key.Contains("Oppma")).Value;

                                ModbusServer.Instance.SendSampleData(sampleNo, float.Parse(cppma), float.Parse(oppma));
                            }
                            catch (Exception ex)
                            {
                                tbx_deviceMessages.AppendText("数据格式错误请检查数据" + Environment.NewLine);
                            }
                            break;
                        // 计算时使用的宏id
                        case "ProcessId":
                            // ProcessChain:503a608b-7e8c-4079-8898-f79e277aedb6
                            var value = cells.LastOrDefault();
                            if (cells.Count > 1 && !string.IsNullOrWhiteSpace(value) && value.StartsWith("ProcessChain:") && value.Length == 49)
                            {
                                AppSettings.Instance.MacroId = cells.Last();
                                AppSettings.Instance.SaveToLocalFile();
                            }

                            break;

                        case "客户端连接":
                            DeviceControl.Instance.Reset();
                            break;
                    }
                }));
            };

            // 注册流程控制消息
            DeviceControl.Instance.MsgCallback = (msg) =>
            {
                Invoke(new Action(() =>
                {
                    tbx_deviceMessages.AppendText(msg + Environment.NewLine);
                }));
            };
            // 启动Modbus服务
            ModbusServer.Instance.Start(Program.ServerLogger, (logTypeEnum, data) =>
            {
                Invoke(new Action(() =>
                {
                    switch (logTypeEnum)
                    {
                        case LogTypeEnum.Msg:
                            tbx_robotArmMessage.AppendText(data + Environment.NewLine);
                            break;

                        case LogTypeEnum.Data:
                            if (!DeviceControl.Instance.BeginTest(data))
                            {
                                tbx_deviceMessages.AppendText($"{DateTime.Now:MM-dd HH:mm:ss},上一个流程还没有结束" + Environment.NewLine);
                            }
                            break;
                    }
                }));
            });
        }

        /// <summary>
        /// 发送消息给设备
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            Dictionary<string, LogicFlowStep> dic = new Dictionary<string, LogicFlowStep>
            {
                { "背景", LogicFlowStep.DeviceScanBackground},
                { "扫描", LogicFlowStep.DeviceScanStart },
                { "选择最新样品", LogicFlowStep.SampleSelectSample },
                { "样品计算", LogicFlowStep.SampleCalculateSample},
                { "样品计算结果", LogicFlowStep.SampleCalculateResult },
                { "删除历史样品", LogicFlowStep.DeleteTreeNode },
            };

            var cmd = comboBox1.Text.Trim();
            if (string.IsNullOrWhiteSpace(cmd))
            {
                tbx_deviceMessages.AppendText("请先选择发送的命令" + Environment.NewLine);
                return;
            }
            if (DeviceControl.Instance.IsExistSample)
            {
                tbx_deviceMessages.AppendText("上一个流程还没有结束" + Environment.NewLine);
                return;
            }
            _ = DeviceControl.Instance.HeadConterol(dic[cmd], cmd);
        }

        /// <summary>
        /// 自动开始流程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            if (!DeviceControl.Instance.BeginTest("A123"))
            {
                tbx_deviceMessages.AppendText("上一个流程还没有结束" + Environment.NewLine);
            }
        }

        /// <summary>
        /// 自动控制等待时长值变化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        [ComVisible(true)]
        private void nud_ValueChanged(object sender, EventArgs e)
        {
            // 更新键值
            AppSettings.Instance.Bjsmddsc = Convert.ToInt32(nud_bjsmddsc.Value);
            AppSettings.Instance.Szypddsc = Convert.ToInt32(nud_szypddsc.Value);
            AppSettings.Instance.Jsddsc = Convert.ToInt32(nud_jsddsc.Value);

            DeviceControl.Instance.logicFlowDic[LogicFlowStep.DeviceScanBackground] = AppSettings.Instance.Bjsmddsc;
            DeviceControl.Instance.logicFlowDic[LogicFlowStep.DeviceScanStart] = AppSettings.Instance.Bjsmddsc;
            DeviceControl.Instance.logicFlowDic[LogicFlowStep.SampleSelectSample] = AppSettings.Instance.Szypddsc;
            DeviceControl.Instance.logicFlowDic[LogicFlowStep.SampleCalculateSample] = AppSettings.Instance.Jsddsc;

            AppSettings.Instance.SaveToLocalFile();
        }
    }
}